/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controlador.Service.Compras;

import Controlador.Bean.Compras.Factura;
import Controlador.Bean.Log.Log;
import Data.config.SessionFac;
import gui.General.Main;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.ibatis.session.SqlSession;

/**
 *
 * @author LiziTa
 */
public class ServicioFactura {
      
       java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date fecha= new Date();
        String f=sdf.format(fecha);
        
    public List<Factura> obtenerFactura(){
    SqlSession sqlsession= SessionFac.SessionFactory().openSession();
    List<Factura> data=sqlsession.selectList("Data.Compras.ServicioFactura.obtenerFactura");
   
    sqlsession.close();
     
    return data;
    }
    
    
            public List<Factura> obtenerFacturaFiltro(String id,String fi,String ff){
        try(SqlSession sqlsession = SessionFac.SessionFactory().openSession()){
             HashMap<String, String> hm = new HashMap<>();
             if (id==null) id="";
        hm.put("id", "%"+id+"%");
          hm.put("fi", fi);
            hm.put("ff", ff);
        List<Factura> data = (List)sqlsession.selectList("Data.Compras.ServicioFactura.obtenerFacturaFiltro",hm);
        sqlsession.close();
        return data;  }
    }
            
    
    
     public void guardar(Factura factura){
     try(SqlSession sqlsession= SessionFac.SessionFactory().openSession()){
         if(factura.getObservacion().isEmpty()) factura.setObservacion("");
         
     factura.setIdfacturacompra(obtenerIdSiguienteFactura());
     sqlsession.insert("Data.Compras.ServicioFactura.guardar", factura);
     sqlsession.commit();
     sqlsession.close();
      Log.setInstancia(Main.usu.getIdEmpleadoAdm(),"CMPFACTU","Guardar Fcatura",f );
       }catch(Exception ex){
            ex.printStackTrace();
        }
}
     
     
     public String obtenerIdSiguienteFactura(){
           try(SqlSession sqlsession= SessionFac.SessionFactory().openSession()){     
         String id= (String)sqlsession.selectOne("Data.Compras.ServicioFactura.getNextCodigo");
        
        if(id!=null){
        int cod= Integer.parseInt(id.substring(3)) + 1;
        
        String defecto= "000000";
        String temp= defecto.substring(0, defecto.length()-String.valueOf(cod).length()).concat(String.valueOf(cod));

        id = (id.substring(0,3).concat(temp));}
        
        else{
        id = "FOC000001"; 
        
        }
           
        return id;}
    }
      
}
